<?php

namespace App\Http\Controllers\Api\Recruit;

use App\Handlers\ImageUploadHandler;
use App\Http\Controllers\Controller;
use App\Inputs\PublishRecruitInput;
use App\Models\Recruit;
use App\Services\RecruitService;
use App\Traits\VerifyFrontEndParameters;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RecruitController extends Controller
{
    use VerifyFrontEndParameters;

    public function testVerify()
    {

        // $this->verifyId('id');
        $input = (new PublishRecruitInput())->fill();
        dd($input);
    }

    /**
     * scale > 14: 默认查询最细颗粒度的数据
     * 12 < scale <= 14: 查询街道的数据
     * scale <= 12: 查询区的数据
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function mapRecruitBubbles(Request $request): JsonResponse
    {
        // 根据当前用户的经纬度查询附近的招工列表
        $rule        = [
            "maxLatitude"   => "required",
            "maxLongitude"  => "required",
            "minLatitude"   => "required",
            "minLongitude"  => "required",
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        try {
            $data = (new RecruitService())->getMapRecruitList($input);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }
        return result(0, 'ok', $data);
    }

    public function recruitListByBubble(Request $request): JsonResponse
    {
        $rule = [
            "region_id"     => "required|integer"
        ];
        $input = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        $recruitTableColumns = ["id", "user_id", "city", "contact_phone", "updated_at", "title"];
        $userTableColumns = ['id', 'avatar', 'nickname'];

        $page  = (int) ($input['page'] ?? 1);
        $limit = isset($input['limit']) && (int) $input['limit'] <= 20 ? (int) $input['limit'] : 10; // 限制分页查询的个数最大是 20
        $sortField  = $input['sort'] ?? 'updated_at';
        $orderRule = $input['order'] ?? 'desc';

        $where = [
            ['status', '=', 2],
            ['region_id', '=', (int) $input['region_id']],
        ];

        try {
            $data = (new RecruitService())->getRecruitList($page, $limit, $sortField, $orderRule, $recruitTableColumns, $userTableColumns, $where);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }
        return result(0, 'ok', $data);
    }

    /**
     * 发布招工
     * @param Request $request
     * @return JsonResponse
     */
    public function publishRecruit(Request $request): JsonResponse
    {
        $rule        = [
            "id"                => "present",
            "user_id"           => "required|integer",
            "title"             => "present|string",
            "recruit_desc"      => "required|string",
            "contact_name"      => "required|string",
            "contact_phone"     => "required|string",
            "salary_info"       => "required|json",
            "recruit_cate_id"   => "required|integer",
            "recruit_cate_name" => "required|string",
            "image"             => "present|max:255",
            "address"           => "required|string",
            "address_detail"    => "required|string",
            "latitude"          => "required|decimal:0,6",
            "longitude"         => "required|decimal:0,6",
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        // laravel 在接收到前端传递的空串时，会自动转换为 null，如果 image 字段设置不为 null，插入数据库时就会报错
        // $input['image'] = $input['image'] ?? '';

        // 2. 入库
        try {
            if ($input['id']) {
                Recruit::query()->where('id', '=', $input['id'])->update($input);
            } else {
                Recruit::query()->insertGetId($input);
            }
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }
        return result(0, '发布成功');
    }

    /**
     * 获取发布的招工详情
     * @param Request $request
     * @return JsonResponse
     */
    public function publishRecruitDetail(Request $request): JsonResponse
    {
        $rule        = [
            "id"      => "required|integer|exists:recruit,id",
            "user_id" => "present|nullable|integer|exists:recruit,id",
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        try {
            $data = (new RecruitService())->getPublishRecruitDetail($input);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }
        return result(0, '获取成功', $data);
    }

    /**
     * 获取招工详情
     * @param Request $request
     * @return JsonResponse
     */
    public function recruitDetail(Request $request): JsonResponse
    {
        $rule        = [
            "recruit_id" => "required|integer",
            "user_id"    => "present|nullable|integer",
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        try {
            $data = (new RecruitService())->getRecruitDetail($input);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }
        return result(0, '获取成功', $data);
    }

    public function uploadFile(Request $request, ImageUploadHandler $uploader): JsonResponse
    {
        $result = ['save_path' => '', 'access_path' => ''];
        // 判断是否有上传文件，并赋值给 $file
        if ($file = $request->upload_file) {
            // 保存图片到本地
            $result = $uploader->save($request->upload_file, 'work-picture', 'wp', 1024);
        }
        return result(0, '上传成功', $result);
    }
}
